package com.jerry.shop.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jerry.shop.bean.Order;
import com.jerry.shop.bean.OrderDetail;
import com.jerry.shop.bean.Product;
import com.jerry.shop.dto.OrderDto;
import com.jerry.shop.enums.ResultEnum;
import com.jerry.shop.exception.SellException;
import com.jerry.shop.form.OrderForm;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class OrderConverter {

    public static OrderDto convert(Order order) {

        OrderDto orderDto = new OrderDto();
        BeanUtils.copyProperties(order, orderDto);

        return orderDto;
    }

    public static List<OrderDto> convert(List<Order> orderList) {

        //使用java8的lamda表达式
        List<OrderDto> orderDtoList = orderList.stream()
                                               .map(e -> convert(e))
                                               .collect(Collectors.toList());

        return orderDtoList;
    }

    public static OrderDto convert(OrderForm orderForm) {
        Gson gson = new Gson();

        OrderDto orderDto = new OrderDto();
        orderDto.setBuyerName(orderForm.getName());
        orderDto.setBuyerPhone(orderForm.getPhone());
        orderDto.setBuyerAddress(orderForm.getAddress());
        orderDto.setBuyerId(orderForm.getId());

        List<OrderDetail> orderDetailList = new ArrayList<>();
        try {
            orderDetailList = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>() {}.getType());
        } catch (Exception e) {
            System.out.println("【对象转换】错误, string=" + orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderDto.setOrderDetailList(orderDetailList);

        return orderDto;
    }
}
